<template>
  <n-modal v-model:show="showAvatarModal">
    <n-card style="width: 600px" title="修改头像" :bordered="false">
      <template #header-extra>
        <n-button quaternary circle @click="emit('close')">
          <template #icon>
            <n-icon><close-icon /></n-icon>
          </template>
        </n-button>
      </template>
      <div class="flex flex-col justify-center items-center">
        <div class="w-3/5">
          <img :src="tmpUserInfo?.avatar" alt="" class="m-auto" />
        </div>
        <div class="mt-3">
          <n-upload
            :max="1"
            @before-upload="beforeUpload"
            :custom-request="uploadFile"
            :show-file-list="false"
          >
            <n-button>上传头像</n-button>
          </n-upload>
        </div>
        <n-text depth="3">
          通过上传和共享此内容，您需要确认您是该内容的所有者，并拥有任何必要的知识产权和个人权利。
        </n-text>
      </div>
      <template #footer>
        <div class="flex justify-end">
          <n-button class="cancel-btn" @click="emit('close')">取消</n-button>
          <n-button type="primary" @click="submit">确定</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { Close as CloseIcon } from '@vicons/ionicons5'
import api from '@/api/api'

const message = useMessage()

const props = defineProps(['tmpUserInfo', 'showAvatarModal'])
const emit = defineEmits()

// 文件上传前检测
const beforeUpload = (data) => {
  if (
    data.file.file?.type !== 'image/png' &&
    data.file.file?.type !== 'image/jpeg'
  ) {
    message.warning('只能上传PNG和JPG文件')
    return false
  } else if (data.file.file?.size > 1000000) {
    message.warning('请确保图片小于1MB')
    return false
  }
  return true
}

// 上传请求
const uploadFile = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  api.Common.uploadFile(formData)
    .then((res) => {
      if (res.success) {
        props.tmpUserInfo.avatar = res.url
        localStorage.setItem('avatar', res.url)
      } else {
        message.error('图片上传失败，请重试')
      }
    })
    .catch(() => {
      message.error('图片上传失败，请重试')
    })
}

const submit = () => {
  emit('submit')
}
</script>

<style scoped>
.cancel-btn {
  margin-right: 1rem;
}
</style>
